﻿using System.Net.NetworkInformation;
using System;
using System.ComponentModel;

namespace OpenLightGroup.Common
{

    public class NetworkStatus 
        : INetworkStatus, INotifyPropertyChanged
    {

        #region Singleton Members

        protected NetworkStatus()
        {
            NetworkChange.NetworkAddressChanged +=
                new NetworkAddressChangedEventHandler(OnNetworkAddressChanged);
        }

        private static INetworkStatus _instance = null;

        public static INetworkStatus Current
        {
            get
            {

                if (_instance == null)
                {
                    _instance = new NetworkStatus();
                }
                return _instance;

            }
        }

        #endregion

        #region INetworkStatus

        public event EventHandler NetworkStatusChanged;

        private bool _isOnline = NetworkInterface.GetIsNetworkAvailable();

        public bool IsOnline
        {
            get
            {
                return this._isOnline;
            }
            protected set
            {
                if (value != this._isOnline)
                {
                    this._isOnline = value;
                    this.NetworkStatusChanged.Raise(this);
                    this.PropertyChanged.Raise(this, "IsOnline");

                }
            }

        }

        protected virtual void OnNetworkAddressChanged(object sender, EventArgs e)
        {
            this.IsOnline = NetworkInterface.GetIsNetworkAvailable();
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }

}